# Copyright (C) 2006  Apptility LLC  http://www.apptility.com
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

class FeedController < ApplicationController
  #require 'rubygems'
  #require_gem 'feedtools'
  require 'feed_tools' 
  
  
  @feedtools_options = {}
  $CURRENT_MAIN_TAB_NAME = "Feeds"
  $CURRENT_SUB_TAB_NAME = "My Feeds"

  def show
    @feed = find_feed(params[:id])
  end

  def delete
    @feed = find_feed(params[:id])
    if(@feed.destroy)
      flash[:simplemsg] = "Feed has been deleted"
    else
      flash[:message] = "Feed can not be deleted"
    end
   redirect_to :action => 'list'
 
  end

      
  def list
    #Feedeliverynotify.deliver_feedeliverynotifysimpletemplate()
    @content_columns = feed_content_columns_to_display
    if($list!=nil)
    @feeds = $list
    @feed_pages, @feeds = paginate :feed, :per_page => 10
    @feeds
    else   
    @feeds = Feed.find(:all, :conditions => [ "user_id =?", current_user.id])
    #@feeds_paginate = Paginator.new self, @feeds.size, @params['page'].to_i
    #@feeds_paginate = paginate :feed, 
    #                          :conditions => [ "user_id =?", current_user.id], 
    #                          :order_by => "updated_at" , 
    #                          :per_page => 1
    #                          
    
    end                          
  end
   
  def newfeed
    @feedurl = params['feedurl']
    @op = params['op']
    @refreshfeedflag = "false"
    # @newOrRefreshFeedLabel = "Feed Me!"
    @newOrRefreshFeedLabel = "btn-getfeed.gif"
    
    return if @feedurl==nil
    
    if(@op!='refresh')
      @feedExists = Feed.find(:first, :conditions=>["feed_url = ?", @feedurl])
    end
    
    if(@feedExists!=nil)
      flash[:notice] = "Feed already exists in your list of feeds, You can refresh the feed data by clicking on 'Refresh' button "
      @refreshfeedflag = "true"
      # @newOrRefreshFeedLabel = "Refresh Me!"
      @newOrRefreshFeedLabel = "btn-refreshfeed.gif" 
      return 
    end  
    #@feedu = FeedTools::Feed.open(@feedurl)
    @h = getFeed(@feedurl) 
   end
  
  def htmlsfc
    @feedid = params['feedid']
    @encodedfeedid = base64encode(@feedid)
    #@todo
    host_with_port = request.host_with_port()
    @htmlsnippet = "<form Method='POST' action='http://"+host_with_port+"/feed/subscribefeed'>Enter your Email<br><input name='subscriberemail' maxlength='255' type='text' size='30' value=""><br><input name='feedid' type='hidden' value='"+@encodedfeedid+"'><input type='submit' value='Subscribe me!'><br>Powered by <a href='"+getPoweredByURL+"'>"+getPoweredByName+"</a></form>"
   end
  
  def subscribefeed
    @encodedfeedid = params['feedid']
    @email = params['subscriberemail']
    return if  @encodedfeedid==nil  or @email==nil
    @feedid = base64decode(@encodedfeedid)
    @feedsubscriber = FeedSubscriber.new()
    @feedsubscriber.feed_id = @feedid
    @feedsubscriber.email = @email
    @feedsubscriber.save
 
    #@todo-Need to change this using activerecord relationship later, now do the crude way
    @feed = Feed.find(@feedid)
  end
  
  def listsubscribers
    @feeds = list
    @feedid = params['feedid']
    @showFeedList = true
    return if (@feedid==nil)
    ##@todo get feed subscriber based on current user->all feeds->subscriber relationship
    #@feed = Feed.find(@feedid)
    @feed = find_feed(@feedid)
    @feedsubscribers = FeedSubscriber.find(:all, :conditions => [ "feed_id = ?", @feedid])
    # @feedsubscribers = @feed.feedsubscribers.find(:all)
    @showFeedList = false
    
  end
   
  def savefeed
    @feedurl = params['feedurl']
    @feed = Feed.find(:first, :conditions=>["feed_url = ?", @feedurl])
    if(@feed==nil)
       @feed  = Feed.new()
    end
       
    @feedtitle = params['feedtitle']
    @feeddescription = params['feeddescription']
    @feedguid = params['feedguid']
    @feedupdated = params['feedupdated']
    
    
    @feed.user_id = current_user.id
    @feed.title = @feedtitle
    @feed.feed_url = @feedurl
    @feed.description = @feeddescription
    @feed.guid = @feedguid
    #AjubyLogger.logInfo "@feedguid up=>" << @feed.guid
    @feed.last_updated_time = @feedupdated
    #AjubyLogger.logInfo "@feed.last_updated_time=>" => @feed.last_updated_time.to_s
    @feed.save

    # Now update Feed Post update right away.in case if we need to deliver post to user right away
    #@todo, have a config flag which can turn this one on and off. useful while testing
    @feedu = FeedTools::Feed.open(@feedurl) 
    @feedpostupdates = FeedPostUpdate.delete_all("feed_id = #{@feed.id}")
    
    for feed_item in @feedu.items
      @feedPostUpdate  = FeedPostUpdate.new()
      @feedPostUpdate.feed_id = @feed.id
      @feedPostUpdate.post_title = feed_item.title
      @feedPostUpdate.post_url = feed_item.link
      @feedPostUpdate.post_content = feed_item.description
      if(feed_item.updated!=nil)
        @feedPostUpdate .post_modified = feed_item.updated
      else
        @feedPostUpdate .post_modified = feed_item.published
      end    
      
      @feedPostUpdate.post_guid = feed_item.id
      @feedPostUpdate.is_alive = 1
      @feedPostUpdate.save
    end
    
    flash[:simplemsg] = "Your feed has been saved."
    redirect_to :action => 'list'
  end
  
  def deliver_now
    @feedid = params['feedid']
    begin
      FeedDeliveryUtil.deliver_now(@feedid)
      flash[:notice] = "Your feed has been delivered to the subscribers. "
      redirect_to :action => 'list'
    rescue Exception => e
      flash[:message] = "Error delivering Feed, because:" << e.message 
       redirect_to :action => 'list'
    end  
  end
 
  def deliverylist
    @feeds = list
    @feedid = params['feedid']
    @showFeedList = true
    return if (@feedid==nil)
    @feedsubscribers = FeedSubscriber.find(:all, :conditions=>["feed_id = ?", @feedid])
    if (@feedsubscribers.size==0)
      flash[:notice] = "No subscribers yet, for this Feed."
      #return
      redirect_back_or_default :action => 'deliverylist'
    end  
    
    @feed = Feed.find(@feedid)
    @op = params['op'] 
    if(@op=='startdelivery')
      @feeddeliverytemplate = params['feeddeliverytemplate'] 
      @feeddeliverytype = params['feeddeliverytype']
      #@todo, new or find, do not create everysingle time
      @feeddelivery = FeedDelivery.new()
      @feeddelivery.feed_id = @feedid
      @feeddelivery.newsletter_id = @feeddeliverytemplate
      @feeddelivery.delivery_type = @feeddeliverytype
      @feeddelivery.save
      
      #@todo  use ActiveRecord relationship here rather than finding things again
      #Following is kludgy..bad!!
      @feeddelivery_type = FeedDeliveryType.find(@feeddeliverytype)
      @feeddelivery_template = FeedNewsletter.find(@feeddeliverytemplate)
      
      @savemessage =  "Your feed #{@feed.feed_url} is scheduled to deliver #{@feeddelivery_type.delivery_type} using #{@feeddelivery_template.name}"
      flash[:notice] = "Your delivery data is saved."
    else
      @feedeliverytypes = FeedDeliveryType.find_all
      @feedenewsletters = FeedNewsletter.find_all
    end
    @showFeedList = false   
  end 
 
  
  def processfeed
    @useremail = current_user.email
    @feedurl = params['feedurl']
    
    @op = params['op']
    if @op==nil
      flash[:notice] = "Process feed: Operation type missing!. "
      return
    end
    if @feedurl==nil
      flash[:notice] = "Feed url is missing!. "
      return
    end  
    
    @op = params['op']
    @useremail = params['emailto']
    if(@op=='email')
       @feedu = FeedTools::Feed.open(@feedurl) 
       FeedNotify.deliver_emailfeed(current_user, @useremail, @feedu)
       flash[:notice] = ' Feed has been emailed to your email account, please verify'
    end
    
   end
   
   protected 
   
   def feed_content_columns_to_display
      # Override this from user engine
      desired_columns = ["id", "user_id", "guid", "last_updated_time", "created_at", "updated_at", "created_by", "updated_by"]
      Feed.content_columns.delete_if { |c| desired_columns.include?(c.name) }
    end
   
   
    def base64encode(rawstring)
      encoded   = Base64.encode64(rawstring)
    end
    def base64decode(encoded)
      decoded = Base64.decode64(encoded)
    end
   
    # A convenience method to find a feed, and add any errors to the flash if
    # the Feed is not found.
    def find_feed(id)
      begin
        Feed.find(id)
      rescue ActiveRecord::RecordNotFound
        flash[:message] = "There is no feed with ID ##{id}"
        nil
      end
    end
       
   #@todo
    def getPoweredByURL
      return "#{LoginEngine.config(:powered_by_url)}"
      
    end
    
   #@todo 
   def getPoweredByName
     return "#{LoginEngine.config(:app_name)}"
    end
    
    def getFeed(feedurl)
      @feedu = nil
      @error_string = ""
      begin
        @feedu = FeedTools::Feed.open(feedurl) 
        @error_string = nil
      rescue => err
        @error_string << err.message
        AjubyLogger.logInfo "##########Error message :" << err.message
      end  
      # fArray = Array.new(@feedu, @error_string)
      h = {'feedobj' => @feedu, 'errorstr' => @error_string}
      return h
 end
    
end
